package com.xm.rsi.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import com.xm.rsi.common.ErrorCode;
import com.xm.rsi.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class EmailUtils {
    
    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.password}")
    private String password;
    
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final String EMAIL_PATTERN =
            "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    
    public void sendEmail(String email, String content) {
        String emailCode = redisTemplate.opsForValue().get(email);
        if (StringUtils.isNotBlank(emailCode)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请勿频繁发送，稍后重试");
        }
        boolean validate = validate(email);
        if (!validate) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入合法的邮箱");
        }
        try {
            Properties properties = new Properties();
            properties.setProperty("mail.host", "smtp.qq.com");
            properties.setProperty("mail.transport.protocol", "smtp");
            properties.setProperty("mail.smtp.auth", "true");

            //QQ存在一个特性设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, password);
                }
            });
            
            session.setDebug(true);
            Transport transport = session.getTransport();
            String host = "smtp.qq.com";
            transport.connect(host, from, password);
            
            //创建一个邮件发送对象
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
            mimeMessage.setSubject("兴萌遥感影像平台");
            if (content == null) {
                String code = randomCode();
                mimeMessage.setContent("您的验证码为" + code + "，有效期为五分钟，请不要将此验证码告知他人，若非您操作，请忽略", "text/html;charset=UTF-8");
                redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
            } else {
                mimeMessage.setContent(content, "text/html;charset=UTF-8");
            }
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            transport.close();
            log.info("成功发送邮箱至：" + email);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "发送邮箱异常");
        }
    }
    
    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
    
    public static boolean validate(final String email) {
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}
